﻿using System;
using System.Collections.Generic;
using System.Text;

namespace ProblemsSet
{
    public class Problem_51 : BaseProblem
    {
        public override object GetResult()
        {
            const int maxval = 8;

            var hsS = new HashSet<string>();
            var hs = new HashSet<long>(MathLogic.GetPrimeList(1000000, true));
            var res = new List<List<long>>();


            foreach (var h in hs)
            {
                var tmp = h.ToString();
                for (var i = 1; i < tmp.Length; i++)
                {
                    var rs = MathLogic.GetMasks(tmp, i);
                    foreach (var r in rs)
                    {
                        if (hsS.Contains(r)) continue;
                        hsS.Add(r);
                        var lst = new List<long>();
                        for (var j = 0; j < 10; j++)
                        {
                            if (lst.Count+10-j < maxval) break;
                            var s = r.Replace("*", j.ToString());
                            if (s.StartsWith("0")) continue;
                            var rsval = Convert.ToInt64(s);
                            if (!hs.Contains(rsval)) continue;
                            lst.Add(rsval);
                        }
                        if (lst.Count < maxval) continue;
                        lst.Sort();
                        res.Add(lst);
                    }
                }
                if (res.Count < 1) continue;
                long mx = 0;
                foreach (var re in res)
                {
                    if (mx == 0 || re[0] < mx) mx = re[0];
                }
                return mx;
            }
            return - 1;

        }

        public override string Problem
        {
            get
            {
                return @"By replacing the 1st digit of *3, it turns out that six of the nine possible values: 13, 23, 43, 53, 73, and 83, are all prime.

By replacing the 3rd and 4th digits of 56**3 with the same digit, this 5-digit number is the first example having seven primes among the ten generated numbers, yielding the family: 56003, 56113, 56333, 56443, 56663, 56773, and 56993. Consequently 56003, being the first member of this family, is the smallest prime with this property.

Find the smallest prime which, by replacing part of the number (not necessarily adjacent digits) with the same digit, is part of an eight prime value family.";
            }
        }

        public override bool IsSolved
        {
            get
            {
                return true;
            }
        }

        public override object Answer
        {
            get
            {
                return 121313;
            }
        }

    }
}
